package city.spring.utils;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求工具类（获取当前请求的IP地址）
 *
 * @author HouKunLin
 * @date 2020/8/11 0011 15:06
 */
public class RequestUtils {
    private static final String[] IP_KEYS = new String[]{"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};

    /**
     * 获得当前请求对象
     *
     * @return 请求对象
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

    /**
     * 获取当前请求的IP
     *
     * @return IP
     */
    public static String getRequestIp() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            return getRequestIp(request);
        }
        return null;
    }

    /**
     * 获取请求的IP
     *
     * @param request 请求对象
     * @return IP
     */
    public static String getRequestIp(HttpServletRequest request) {
        String ip = null;
        for (int i = 0; i < IP_KEYS.length; i++) {
            ip = request.getHeader(IP_KEYS[i]);
            if (isNotEmpty(ip)) {
                break;
            }
            if (i == IP_KEYS.length - 1) {
                ip = request.getRemoteAddr();
            }
        }
        return obtainIp(ip);
    }

    /**
     * 判断IP是否为空
     *
     * @param ip IP内容
     * @return 结果
     */
    private static boolean isNotEmpty(String ip) {
        return StringUtils.isNotBlank(ip) && !"unknown".equals(ip.toLowerCase());
    }

    /**
     * 获取IP信息（去除本机的IPv6地址）
     *
     * @param ip IP内容
     * @return IP信息
     */
    private static String obtainIp(String ip) {
        if (ArrayUtils.contains(new String[]{"0:0:0:0:0:0:0:1", "::1"}, ip)) {
            return "127.0.0.1";
        }
        return ip;
    }
}
